<template>
  <div class="home">
    <ul ref="messagesRef" id="messages">
      <li>hello</li>
      <li>world</li>
      <li v-for="(message, index) in messages" :key="index">{{ message }}</li>
    </ul>
    <form ref="formRef" id="form" @submit.prevent="sendMessage">
      <input id="input" v-model="message" autocomplete="off" /><button>
        Send
      </button>
    </form>
  </div>
</template>

<script setup>
import { ref } from "vue";
import io from "socket.io-client";
import { useStore } from "vuex";

const store = useStore();
const message = ref("");
const messages = ref([]);
// url会自动添加socket.io的路径
const socket = io("http://localhost:3000/", {
  reconnectionDelayMax: 10000, // 最大重连时间
  auth: {
    // 认证信息
    token: store.state.user.token,
  },
  query: {
    // 查询参数
    "my-key": "my-value",
  },
  extraHeaders: {}, // 额外的请求头
});

socket.on("connect", () => {
  console.log("连接建立成功");
});

// 发送消息
const sendMessage = () => {
  console.log("first", message.value.trim());
  if (message.value.trim()) {
    socket.emit("chat message", message.value);
    message.value = "";
  }
};

// 接收消息
socket.on("chat message", (data) => {
  messages.value.push(data);
});

socket.on("disconnect", () => {
  console.log("连接断开");
});

socket.on("connect_error", (error) => {
  console.log("连接失败", error);
});
</script>

<style scoped>
body {
  margin: 0;
  padding-bottom: 3rem;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
    Arial, sans-serif;
}

#form {
  background: rgba(0, 0, 0, 0.15);
  padding: 0.25rem;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  height: 3rem;
  box-sizing: border-box;
  backdrop-filter: blur(10px);
}
#input {
  border: none;
  padding: 0 1rem;
  flex-grow: 1;
  border-radius: 2rem;
  margin: 0.25rem;
}
#input:focus {
  outline: none;
}
#form > button {
  background: #333;
  border: none;
  padding: 0 1rem;
  margin: 0.25rem;
  border-radius: 3px;
  outline: none;
  color: #fff;
}

#messages {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
#messages > li {
  padding: 0.5rem 1rem;
}
#messages > li:nth-child(odd) {
  background: #efefef;
}
</style>
